package com.xohm.diagonstic.tool;

import com.xohm.base.logging.*;
import com.xohm.base.*;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * Xohm Connection Manager
 *
 * Licensed Material - Property of Sprint Nextel
 * Restricted Materials of Sprint Nextel
 * (C) Copyright Sprint Nextel Corp. 2008 - All Rights Reserved.
 *
 * Temporary WebServer Implementation for the Mac since it isn't on the
 * 1.6 JRE version yet.  When they get their act together then we can use
 * the 1.6 HTTP Light Weight Server built into the JRE.
 *
 * @author Robin Katzer 
 */

public class WebServer implements HttpConstants
{
	private static WebServer singleton = null;
	private Thread serverThread = null;
	
	private int port = 9823;
	public Vector<Worker> threads = new Vector<Worker>();
	public File root = new File(System.getProperty("user.dir")); // Servers virtual root
	public int timeout = 5000;
	private int workers = 2;  // 2 threads
	
	public Driver driver = null;

	private WebServer() {	}
	
	public static WebServer getInstance()
	{
		if (singleton == null)
		{
			singleton = new WebServer();
			singleton.initialize();
		}
		
		return singleton;
	}
	
	public static void main(String[] args)
	{
		WebServer.getInstance();
	}
	
	private void initialize()
	{
		/* start worker threads */
		for (int i = 0; i < workers; ++i)
		{
			Worker worker = new Worker(this);
			(new Thread(worker, "worker #" + i)).start();
			threads.addElement(worker);
		}

		Runnable server = new Runnable()
		{
			public void run()
			{
				try
				{
					ServerSocket serverSocket = new ServerSocket(port);
					while (true)
					{
						Socket socket = serverSocket.accept();
						Worker worker = null;

						synchronized (threads)
						{
							if (threads.isEmpty())
							{
								// Can only allow max of 2 connections
								socket.close();
							}
							else
							{
								worker = (Worker)threads.elementAt(0);
								threads.removeElementAt(0);
								worker.setSocket(socket);
							}
						}
					}
				}
				catch (Exception e)
				{
					XohmLogger.warningPrintln("Diagnostic WebServer has failed: "+e.toString(), null, null);
				}
			}
		};
		
		serverThread = new Thread(server);
		serverThread.start();
		
		XohmLogger.println("Diagnostics server running on port: "+port+", using "+workers+" threads.", null, null);
	}
	
	public void setDriver(Driver driver)
	{
		this.driver = driver;
	}
}